<?php
/**
 * Users Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  MIAOCMS
 * @version  1.0
 * @author   Arlon <MIAOCMS@google.com>

 * @link     http://www.MIAOCMS.net
 */

App::uses('EasemobUtility','Utility'); // 环信群组

class UsersController extends AppController {

    var $name = 'Users';
   
    var  $components = array(
		'Email', 
    	'Kcaptcha',
    	//'Securimage',
	);


    public function admin_resetEasePwdAll() {
        $page = 1;
        do{
            $users = $this->User->find('all',array(
                'conditions'=>array(),
                'limit' => 200,
                'recursive' => 1,
                'fields' => array('User.id','User.invite_code'),
                'page' => $page,
            ));
            echo "====$page=====\n\n";
            foreach($users as $u) {
                $ret = EasemobUtility::setPassword($u['User']['id'],$u['User']['invite_code']);
                echo "User:".$u['User']['id']."  ";print_r($ret);echo "\r\n";
            }

            $page++;
        }while( count($users) > 0 );
        echo "\r\nover\r\n";
        exit;
    }

    public function admin_setEasemodPwd($uid){
        $userinfo = $this->User->find('first',array(
            'conditions' => array('User.id' => $uid),
            'recursive' => -1,
        ));
        if(!empty($userinfo)){
            $ret = EasemobUtility::setPassword($uid,$userinfo['User']['invite_code']);
            if($ret['error']){
                echo json_encode(array( 'ret'=>-1,'msg'=> $ret['error'] ));
            }
            else{
                echo json_encode(array('ret'=>0,'msg'=>'设置成功'));
            }
        }
        else{
            echo json_encode(array('ret'=>-1,'msg'=>'设置失败'));
        }
        exit;
    }
    
    function admin_forget(){
        
        if(!empty($this->data['User']['email'])) {
            $userinfo = $this->User->find('first',array(
                'conditions' => array('email' => $this->data['User']['email']),
            ));
            //print_r($userinfo);
            $url = Configure::read('Site.url').'users/reset/'.$userinfo['User']['id'].'/'.$userinfo['User']['activation_key'];
            $this->set('url',$url);
        }
    }
    
    public function admin_batchadd(){
        
        if( !empty($_POST) ) {
            $users = explode("\r\n",$this->data['User']['user_id']);
            $users = array_unique($users);
            $added = 0; $skiped = 0;
            foreach($users as $u) {
                $u = trim($u);
                if(empty($u)) {
                    continue;
                }
                $data = array();
            
                if( $this->data['User']['user_type'] == 'mobile' ) {
                    $conditions = array('mobile'=>$u);
                    $data['mobile'] = $u;
                }
                elseif( $this->data['User']['user_type'] == 'email' ) {
                    $conditions = array( 'email'=> $u );
                    $data['email'] = $u;
                }
                $data['activation_key'] = md5(uniqid());
                $data['invite_code'] = md5(uniqid());
                $data['password'] = Security::hash( random_str(12) , null, true);
                $data['role_id'] = 2;
            
                if( $this->data['User']['user_type'] == 'mobile') { // 新增用户时，保证手机号不出现重复
                    $user = $this->User->getUserByMobile( $u );
                    if(!empty($user)) {
                        $skiped ++;
                        continue;
                    }
                }
                if(  $this->data['User']['user_type'] == 'email'  ) { // 新增用户时，保证手机号不出现重复
                    $user = $this->User->getUserByEmail( $u );
                    if(!empty($user)) {
                        $skiped ++;
                        continue;
                    }
                }
                $this->User->create();
                $this->User->save($data);
                $added ++;
            }
            echo json_encode(array('ret'=> 0,'msg'=>'用户批量增加,新增'.$added.'，忽略'.$skiped.'。','tasks'=> array(array('dotype'=>'reset'))));
            exit;
        }
    }
    
    function admin_add() {
        if ( !empty($this->data) ) {
            $this->data['User']['activation_key'] = md5(uniqid());
            $this->data['User']['invite_code'] = md5(uniqid());
            if( empty($this->data['User']['password']) ) {
                $this->data['User']['password'] = random_str(12);
            }
            $this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
            
            if( !empty($this->data['User']['mobile']) ) { // 新增用户时，保证手机号不出现重复
                $user = $this->User->getUserByMobile( $this->data['User']['mobile'] );
                
                if(!empty($user)) {
                    $errorinfo = array('ret'=>-1,'msg' => __('User mobile exists.'));
                    echo json_encode($errorinfo);
                    exit;
                }
            }
            if( !empty($this->data['User']['email']) ) { // 新增用户时，保证手机号不出现重复
                $user = $this->User->getUserByEmail( $this->data['User']['email'] );
                if(!empty($user)) {
                    $errorinfo = array('ret'=>-1,'msg' => __('User email exists.'));
                    echo json_encode($errorinfo);
                    exit;
                }
            }
        }
        parent::admin_add();
        
    	if ( empty($this->data) ) {
           $this->data['User']['role_id'] = 2; // default Role: Registered
        }
        
        $roles = $this->User->Role->find('list');
        $this->set('roles',$roles);
    }

    function admin_edit($id='',$copy=null) {
    	if (!$id){
       		$id = $this->_getParamVars('id');
		}		
        if (!$id && empty($this->data)) {
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
        	$this->autoRender = false;
        	if(empty($this->data['User']['password'])){
        		unset($this->data['User']['password']);
        	}
        	else{
        		$this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
        	}
        	
        	$updateinfo = array();
        	foreach($this->data['User'] as $key=> $val){
        		if(is_array($val)){
        			$updateinfo[$key] = $this->User->escape_string(','.implode(',',$val).',' );
        		}
        		else{
        			$updateinfo[$key] = $this->User->escape_string($val);
        		}
        		
        	}
        	
            if ($this->User->updateAll($updateinfo,array('User.id'=>$id))) {
                $successinfo = array('success'=>__('Edit success',true));
            }
	        else{
	        	$successinfo = array('error'=>__('Edit error',true));
	        }
	        echo json_encode($successinfo);
        	exit;
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
            $this->__loadFormValues($this->modelClass, $id);
        }
        $roles = $this->User->Role->find('list');
        $this->set(array('roles'=>$roles,'id'=>$id));
        $this->__viewFileName = 'admin_add';
    }
}
?>